package com.msmall.base.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ImageUtil {

	public static final int DEFAULT_WIDTH = 100;
	public static final int DEFAULT_HEIGHT = 90;
	/**
	 * 不包含 constant.rootpath
	 */
	public static int[] getWidthHeight(String imgfile){
		try{
			if(imgfile.startsWith("/")){
				imgfile = imgfile.substring(1);
			}
			String path = Constants.ROOTPATH + imgfile;
			BufferedImage bi = ImageIO.read(new File(path));  
			//原始图片属性  
			int srcWidth = bi.getWidth();  
			int srcHeight = bi.getHeight();
			return new int[]{srcWidth, srcHeight};
		}catch(Exception e){
			return new int[]{DEFAULT_WIDTH, DEFAULT_HEIGHT};
		}
	}
	
	/**
	 * 裁剪图片成为正方形，不足用白色填充。
	 * 如果源图宽高都大于正方形边长，把较长边对称截成较短边长度，然后等比例压缩至正方形尺寸。
	 * 如果源图宽高都不大于正方形边长，采用周边对称填充的方法，达到正方形尺寸
	 * 如果宽高一边大于正方形边长，一边小于正方形边长，把长边对称截成正方形边长，另一边对称填充至正方形尺寸
	 * @param srcImage 原图
	 * @param tarSize 目标正方形尺寸
	 */
	public static BufferedImage scale(BufferedImage srcImage, int tarSize) {
		int width = srcImage.getWidth();
		int height = srcImage.getHeight();
		if (width == tarSize && height == tarSize) {
			return srcImage;
		}
		BufferedImage tarImage = new BufferedImage(tarSize,tarSize,BufferedImage.TYPE_INT_RGB);
		Graphics2D g2 = tarImage.createGraphics();
		g2.setColor(Color.WHITE);
		g2.fillRect(0, 0, tarSize, tarSize);
		BufferedImage tempImage = null;
		
		if (width > tarSize && height > tarSize) {//情况一
			int x = 0;
			int y = 0;
			int size = 0;
			if (width >= height) {
				x = (width-height)/2;
				size = height;
			} else {
				y = (height-width)/2;
				size = width;
			}
			//裁剪成正方形
			tempImage = srcImage.getSubimage(x, y, size, size);
			g2.drawImage(tempImage.getScaledInstance(tarSize, tarSize, Image.SCALE_SMOOTH), 0, 0, null);
		} else if (width <= tarSize && height <= tarSize) {//情况二
			int x = (tarSize-width)/2;
			int y = (tarSize-height)/2;
			g2.drawImage(srcImage.getScaledInstance(width, height, Image.SCALE_SMOOTH), x, y, null);
		} else {//情况三
			int x = 0;
			int y = 0;
			int w = width;
			int h = height;
			if (width > height) {
				x = (width-tarSize)/2;
				w = tarSize;
			} else {
				y = (height-tarSize)/2;
				h = tarSize;
			}
			//裁剪成第二种情况
			tempImage = srcImage.getSubimage(x, y, w, h);
			x = (tarSize-w)/2;
			y = (tarSize-h)/2;
			g2.drawImage(tempImage.getScaledInstance(w, h, Image.SCALE_SMOOTH), x, y, null);
		}
		g2.dispose();
		return tarImage;
	}
}
